package com.hg.util.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.jdiy.core.Rs;

import com.hg.admin.service.AdminService;
import com.hg.admin.vo.VO4admin;
import com.hg.cache.FIFOCache;
import com.hg.forSearch.db.dto.ForSearchDTO;
import com.hg.forSearch.service.ForSearchService;
import com.hg.util.common.Common;
import com.hg.util.common.UserAgentUtil;
import com.hg.util.db.JDiyUtil;
import com.hg.util.db.Locale;
import com.hg.util.http.CookieHelper;
import com.hg.wap.service.UserService;
import com.hg.wap.vo.VO4UserLogin;
import com.hg.wap.vo.VO4user;

public class WapMbaseAction extends MbaseAction
{
	/**
	 * 从内存中获取数据库的缓存
	 * @param root
	 * @return
	 */
	public Map<String,String> getConfig(Map root){
		FIFOCache<String, Object> cache = (FIFOCache<String, Object>) root.get("cache");
		Map<String,String> m_config=(Map<String, String>) cache.get("m_config");
		
		if(null==m_config){
			ForSearchService forS = new ForSearchService();
			
			List<ForSearchDTO> list=forS.getAll("hh_base_m_config_search");
			m_config= new HashMap<String,String>();
			for(int i=0;i<list.size();i++){
				ForSearchDTO dto = list.get(i);
				m_config.put(dto.getId(), dto.getName());
			}
			
			cache.put("m_config", m_config);
		}
		
		return m_config;
	}
	
	public void global_run(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		String cs = "com.hg.util.action.WapMbaseAction";	//类的路径
		Class c=null;
		try
		{
			c = Class.forName(cs);
			String folder_name = (String) root.get("folder_name");
			String check_login_action="";
			if(!"weixin".equals(folder_name)){
				check_login_action="check"+Common.UpStr(folder_name)+"Login";
			}else{
				check_login_action="checkWapLogin";
			}
			
			boolean is_check=false;
			try{
				Method check_m = c.getMethod(check_login_action,Map.class);
				is_check=(boolean) check_m.invoke(c.newInstance(), root);	//TODO 根据应用入口不同,使用不同方式检查是否登录
			}catch(Exception e){
				e.printStackTrace();
			}
			
			if(!is_check){
				//执行到这里,说明没有登录
				String module =(String) root.get("module");
				
				if("user".equals(module)){
					return;
				}else{
					String user_agent = (String) root.get("user_agent");
					//test(user_agent, "user_agent---");
					//user_agent="Mozilla/5.0 (Linux; Android 4.2.2; HUAWEI G6-T00 Build/HuaweiG6-T00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036872 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN";
					
					boolean is_weixin = UserAgentUtil.isWeixin(user_agent);
					if(is_weixin){
						//跳转到微信
						String openid = request.getParameter("openid");
						String user_id = request.getParameter("user_id");
						
						//openid="oFNE7uD0sC5vFNFwxiYjTHmQ45jc";
						//user_id="2009104";
						if("".equals(openid) || openid==null){
							weixin_oauth2(root);
						}else{
							//test(openid, "openid---"+user_id);
							//自动登
							try{
								String action = folder_name+"AutoLogin";
								Method m = c.getMethod(action,Map.class,String.class,String.class);
								Object o=m.invoke(c.newInstance(), root,openid,user_id);
							}catch(Exception e){
								e.printStackTrace();
								jumpToUserLogin(root);
							}
							
						}
						
					}else{
						jumpToUserLogin(root);
					}
				}
			}
		}
		catch (ClassNotFoundException e1)
		{
			e1.printStackTrace();
			jumpToUserLogin(root);
		}
		
		
	}
	
	/**
	 * TODO
	 * wap端的登录
	 * @param root
	 * @param openid
	 * @param user_id  目前是0
	 */
	public void weixinAutoLogin(Map root ,String openid,String user_id){
		UserService us = new UserService();
		VO4UserLogin vo  = us.getRow(openid, user_id);
		if(null!=vo){
			//成功登录
			bindingRelationshipForLink(vo, root); //链接邀请绑定上下级关系	//TODO
			initWapLogined(vo, root); //登录成功后的操作
		}else{
			jumpToUserLogin(root);
		}
	}
	
	/**
	 * TODO
	 * 管理员移动端的登录
	 * @param root
	 * @param openid
	 * @param user_id  目前是0
	 */
	public void adminWapAutoLogin(Map root ,String openid,String user_id){
		UserService us = new UserService();
		VO4UserLogin vo  = us.getRow(openid, user_id);
		if(null!=vo){
			//有改会员,检查该会员是否绑定了管理员账号
			AdminService as = new AdminService();
			VO4admin admin_vo = as.getRowByUserId(vo.getId()+"");
			if(null!=admin_vo){
				initWapLogined(vo, root); //登录成功后的操作,移动端的业务
				initAdminWapLogined(admin_vo, vo, root); 	//登录成功后的操作,管理端的业务
			}else{
				jumpToUserLogin(root);
			}
		}else{
			jumpToUserLogin(root);
		}
	}
	
	/**
	 * 拦截存储测试数据
	 * @param json_str
	 * @param text_str
	 */
	private void test(String json_str,String text_str){
		String test_table = "hh_"+"test";
		
		Rs rs = new Rs(test_table);
		rs.set("json_str", json_str);
		rs.set("text_str", text_str);
		
		JDiyUtil.getDAO().save(rs);
	}
	
	/**
	 * 跳转去微信登录界面
	 * @param root
	 */
	private void jumpToUserLogin(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		String url = Common.getProjectUrl(request)+"/"+root.get("folder_name")+"/user/login.do";
		try
		{
			response.sendRedirect(url);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	

	/**
	 * 跳转去微信授权
	 */
	private void weixin_oauth2(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		
		Map<String,String> m_config=getConfig(root);
		String weixin_login_mode_str = m_config.get("weixin_login_mode").trim();
		int weixin_login_mode=0;
		try{
			weixin_login_mode = Integer.parseInt(weixin_login_mode_str);
		}catch(Exception e){
			e.printStackTrace();
			jumpToUserLogin(root);
		}
		
		boolean is_jump_weixin = true;
		String weixinApi_url="";
		String weixin_config_is_user_table = m_config.get("weixin_config_is_user_table").trim();
		if("1".equals(weixin_config_is_user_table)){
			//从数据库里面取
			weixinApi_url =m_config.get("weixin_config_weixinApi_url").trim();
		}else{
			//从配置文件里面取
			weixinApi_url = Locale.DBG.getString("weixinApi_url");
		}
		
		String url =weixinApi_url;
		switch (weixin_login_mode) {
			case 2:{
				//授权获取
				url=url+"openid/userinfoCode.do?key="+Common.createNoncestr();
				break;
			}
	        case 1:{
	        	url=url+"openid/baseCode.do?key="+Common.createNoncestr();
	        	break;
	        }
	        default:
	        	is_jump_weixin=false;
		}
		
		if(is_jump_weixin){
			String return_url =null;	
			String queryStr=request.getQueryString();
			if(queryStr==null || "".equals(queryStr)){
				//没有参数
				return_url = (request.getRequestURL()).toString();
			}else{
				return_url = (request.getRequestURL() + "?" + queryStr).toString();
			}
			
			url = url + "&hg_return_url="+Common.UrlEncode(return_url);
			try
			{
				response.sendRedirect(url);
			}
			catch (IOException e)
			{
				e.printStackTrace();
				jumpToUserLogin(root);
			}
		}
	}
	
	
	
	/**
	 * 检查是否已经登录
	 * @param request
	 * @return
	 */
	public boolean checkWapLogin(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpSession session = request.getSession();
		Cookie usercookie = CookieHelper.getCookie(request, "user");
		Cookie idcookie = CookieHelper.getCookie(request, "id");
		if(usercookie!=null && idcookie!=null){
			String cookie_user_name=null;
			String cookie_id=null;
			try
			{
				cookie_user_name = URLDecoder.decode(usercookie.getValue(), "UTF-8");
				cookie_id = URLDecoder.decode(idcookie.getValue(), "UTF-8");
				
				String user = (String)session.getAttribute("user");
				String id = (String)session.getAttribute("id");
				
				if(user!=null && id!=null){
					if(user.equals(cookie_user_name) && id.equals(cookie_id)){
						return true;
					}
				}else{
					UserService us = new UserService();
					VO4UserLogin vo = us.getRow(cookie_id);
					if(null!=vo){
						initWapLogined(vo, root);
						return true;
					}else{
						return false;
					}
				}
			}
			catch (UnsupportedEncodingException e)
			{
				e.printStackTrace();
			}
		}
		
		return false;
	}
	
	/**
	 * 检查管理员移动端是否登录
	 * @param root
	 * @return
	 */
	public boolean checkAdminWapLogin(Map root){
		return checkAdminLogin(root);
	}
	
	/**
	 * 登录成功以后的初始化
	 * @param vo
	 */
	public void initWapLogined(VO4UserLogin vo,Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		
		HttpSession session = request.getSession();
		
		session.invalidate();
		session = request.getSession();
		String userName=vo.getUser_name();
		String id = vo.getId()+"";
		session.setAttribute("user", userName);
		session.setAttribute("id", id);
		session.setAttribute("user_info", vo);
		
		try
		{
			userName = URLEncoder.encode(userName, "utf-8");
			id = URLEncoder.encode(id, "utf-8");
			CookieHelper.setCookie(response, "user", userName);
			CookieHelper.setCookie(response, "id", id);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 管理员移动端登录成功后,除了wap端的业务之外的其他业务
	 * @param vo
	 * @param root
	 */
	public void initAdminWapLogined(VO4admin admin_vo,VO4UserLogin vo,Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		
		HttpSession session = request.getSession();
		//session.setAttribute("admin_info", admin_vo);
		session.setAttribute("username", admin_vo.getUsername());
		session.setAttribute("userId", admin_vo.getId());
	}
	
	/**
	 * 退出以后的初始化
	 * @param vo
	 */
	public void initWapLogout(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		
		session.setAttribute("user", null);
		session.setAttribute("id", null);
		session.setAttribute("user_info", null);
		session.setAttribute("admin_info", null);
		CookieHelper.removeCookie(response, CookieHelper.getCookie(request, "user"));
		CookieHelper.removeCookie(response, CookieHelper.getCookie(request, "id"));
	}
	
	/**
	 * 链接推广,绑定上下级关系
	 * 条件:
	 * 		1.请求的地址中包含kmy_id参数
	 */
	public void bindingRelationshipForLink(VO4UserLogin vo,Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		String kmy_id_str = request.getParameter("kmy_id");
		if(!"".equals(kmy_id_str) && kmy_id_str!=null){
			//有传递了kmy_id
			try{
				int kmy_id = Integer.parseInt(kmy_id_str);
				if(kmy_id>0){
					//验证完了kmy_id分销ID的有效性
					if(kmy_id!=vo.getId()){
						//推广ID不是自己
						if(0==vo.getPid()){
							//登录的用户还没有绑定上下级关系
							//检查kmy_id用户是否存在
							UserService us = new UserService();
							VO4UserLogin pvo = us.getRow(kmy_id_str); //查回推广的人
							if(null!=pvo){
								if(vo.getId()!=pvo.getPid() && vo.getId()!=pvo.getPid1() && vo.getId()!=pvo.getPid2()){
									//绑定三级关系
									us.bindingRelationship(vo.getId(), pvo.getId(), pvo.getPid(), pvo.getPid1());
								}else{
									//后面会考虑把"当前登录用户"是推广人用户的上三级的用户记下来
								}
							}else{
								//推广人ID查不到用户,后面会考虑把"没有推广用户"的用户记录下来
								
							}
						}
					}else{
						//后面会考虑把"推广ID"是自己的用户记录下来
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
}
